﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace NetOpen_System.Component
{
    /// <summary>
    /// xml节点属性读取器
    /// </summary>
    public class XmlAttributeReader
    {
        XmlAttributeCollection m_Attributes;
        /// <summary>
        /// 实例化xml节点属性读取器
        /// </summary>
        /// <param name="attributes">xml节点属性集合</param>
        public XmlAttributeReader(XmlAttributeCollection attributes)
        {
            m_Attributes = attributes;
        }
        /// <summary>
        /// 获取字符串
        /// </summary>
        /// <param name="key">属性名</param>
        /// <param name="defaultValue">默认值</param>
        public string GetString(string key, string defaultValue)
        {
            if (m_Attributes[key] != null
                && !stringIsNullOrEmpty(m_Attributes[key].Value))
                return m_Attributes[key].Value;
            return defaultValue;
        }

        /// <summary>
        /// 获取整数
        /// </summary>
        /// <param name="key">属性名</param>
        /// <param name="defaultValue">默认值</param>
        public int GetInt(string key, int defaultValue)
        {
            int val = defaultValue;

            if (m_Attributes[key] != null
                && !stringIsNullOrEmpty(m_Attributes[key].Value))
            {
                try
                {
                    return int.Parse(m_Attributes[key].Value);
                }
                catch
                {
                    return defaultValue;
                }
            }
            return val;
        }

        /// <summary>
        /// 获取布尔值
        /// </summary>
        /// <param name="key">属性名</param>
        /// <param name="defaultValue">默认值</param>
        public bool GetBoolean(string key, bool defaultValue)
        {
            bool val = defaultValue;

            if (m_Attributes[key] != null
                && !stringIsNullOrEmpty(m_Attributes[key].Value))
            {
                try
                {
                    return bool.Parse(m_Attributes[key].Value);
                }
                catch
                {
                    return defaultValue;
                }
            }
            return val;
        }

        /// <summary>
        /// 获取整数
        /// </summary>
        /// <param name="key">属性名</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="minValue">最小值</param>
        public int GetInt(string key, int defaultValue, int minValue)
        {
            int r = GetInt(key, defaultValue);
            return Math.Max(r, minValue);
        }

        private bool stringIsNullOrEmpty(string s)
        {
            return (s == null || s == string.Empty);
        }

    }
}
